<template>
  <div class="forget-password-page">
    <div class="forget-password-container">
      <div class="header">
        <van-icon name="arrow-left" class="back-icon" @click="goBack" />
        <h1>忘记密码</h1>
      </div>
      
      <div class="form-group">
        <div class="input-wrapper">
          <van-icon name="phone" class="input-icon" />
          <input type="tel" placeholder="请输入手机号" v-model="phone" maxlength="11" />
        </div>
        
        <div class="input-wrapper verify-code-wrapper">
          <van-icon name="verify" class="input-icon" />
          <input type="text" placeholder="请输入验证码" v-model="verifyCode" maxlength="6" />
          <van-button 
            type="default" 
            size="small" 
            class="send-code-btn"
            :disabled="countingDown"
            @click="sendVerifyCode"
          >
            {{ countingDown ? `${count}秒后重新发送` : '发送验证码' }}
          </van-button>
        </div>
        
        <div class="input-wrapper">
          <van-icon name="lock" class="input-icon" />
          <input type="password" placeholder="请设置新密码" v-model="newPassword" />
        </div>
        
        <div class="input-wrapper">
          <van-icon name="lock" class="input-icon" />
          <input type="password" placeholder="请确认新密码" v-model="confirmPassword" />
        </div>
        
        <van-button type="primary" size="large" class="reset-button" @click="handleResetPassword">
          重置密码
        </van-button>
      </div>
    </div>
  </div>
</template>

<script>
import { api } from '../api'
import { showToast, showLoadingToast } from 'vant'

export default {
  name: 'ForgetPassword',
  data() {
    return {
      phone: '',
      verifyCode: '',
      newPassword: '',
      confirmPassword: '',
      tempToken: '',
      countingDown: false,
      count: 60,
      timer: null
    }
  },
  beforeUnmount() {
    if (this.timer) {
      clearInterval(this.timer)
    }
  },
  methods: {
    // 返回上一页
    goBack() {
      this.$router.back()
    },
    
    // 发送验证码
    async sendVerifyCode() {
      // 表单验证
      if (!this.phone.trim()) {
        showToast('请输入手机号')
        return
      }
      
      if (!/^1\d{10}$/.test(this.phone)) {
        showToast('手机号格式不正确')
        return
      }
      
      try {
        // 显示加载中
        showLoadingToast({ message: '发送中...', duration: 0 })
        
        // 调用真实的发送验证码API
        const res = await api.sendVerifyCode({ phone: this.phone })
        
        // 存储临时token，后续重置密码时需要使用
        this.tempToken = res.data.temp_token
        
        // 显示成功提示
        showToast({ message: '验证码已发送', type: 'success' })
        
        // 开始倒计时
        this.startCountdown()
        
        console.log('验证码已发送到手机:', this.phone)
        
      } catch (error) {
        console.error('发送验证码失败:', error)
        showToast(error.response?.data?.msg || '发送验证码失败，请稍后重试')
        // 发送失败时清除倒计时
        this.countingDown = false
        this.count = 60
      }
    },
    
    // 开始倒计时
    startCountdown() {
      this.countingDown = true
      this.count = 60
      
      this.timer = setInterval(() => {
        this.count--
        if (this.count <= 0) {
          clearInterval(this.timer)
          this.countingDown = false
        }
      }, 1000)
    },
    
    // 处理重置密码
    async handleResetPassword() {
      // 表单验证
      if (!this.phone.trim()) {
        showToast('请输入手机号')
        return
      }
      
      if (!/^1\d{10}$/.test(this.phone)) {
        showToast('手机号格式不正确')
        return
      }
      
      if (!this.verifyCode.trim()) {
        showToast('请输入验证码')
        return
      }
      
      if (!/^\d{6}$/.test(this.verifyCode)) {
        showToast('验证码格式不正确')
        return
      }
      
      if (!this.newPassword.trim()) {
        showToast('请设置新密码')
        return
      }
      
      if (this.newPassword.length < 6) {
        showToast('密码长度至少为6位')
        return
      }
      
      if (this.newPassword !== this.confirmPassword) {
        showToast('两次输入的密码不一致')
        return
      }
      
      if (!this.tempToken) {
        showToast('请先获取验证码')
        return
      }
      
      try {
        // 显示加载中
        showLoadingToast({ message: '重置中...', duration: 0 })
        
        // 调用真实的忘记密码API接口
        await api.forgetPassword({
          phone: this.phone,
          verify_code: this.verifyCode,
          new_password: this.newPassword,
          temp_token: this.tempToken
        })
        
        // 显示成功提示
        showToast({ message: '密码重置成功', type: 'success' })
        
        console.log('用户密码重置成功:', this.phone)
        
        // 重置成功后跳转到登录页面
        setTimeout(() => {
          this.$router.push('/login')
        }, 1500)
        
      } catch (error) {
        console.error('重置密码失败:', error)
        showToast(error.response?.data?.msg || '重置密码失败，请稍后重试')
      }
    }
  }
}
</script>

<style scoped>
.forget-password-page {
  height: 100vh;
  background-color: #f8f8f8;
}

.forget-password-container {
  width: 100%;
  background-color: #fff;
  min-height: 100vh;
  padding-bottom: 30px;
}

.header {
  display: flex;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.back-icon {
  font-size: 20px;
  margin-right: 20px;
}

.header h1 {
  margin: 0;
  font-size: 18px;
  font-weight: bold;
}

.form-group {
  padding: 20px 15px;
}

.input-wrapper {
  position: relative;
  margin-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.verify-code-wrapper {
  display: flex;
  align-items: center;
  border-bottom: 1px solid #eee;
  padding-bottom: 8px;
}

.verify-code-wrapper input {
  flex: 1;
}

.input-icon {
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
  z-index: 1;
}

.send-code-btn {
  padding: 6px 12px;
  font-size: 13px;
  border: 1px solid #1989fa;
  color: #1989fa;
  background-color: transparent;
  margin-left: 10px;
}

.send-code-btn:disabled {
  border-color: #ccc;
  color: #ccc;
}

.input-wrapper input {
  width: 100%;
  padding: 12px 0 12px 30px;
  border: none;
  outline: none;
  font-size: 16px;
}

.input-wrapper input::placeholder {
  color: #999;
}

.reset-button {
  width: 100%;
  margin-top: 30px;
  padding: 12px 0;
  font-size: 16px;
  border-radius: 8px;
}
</style>